package com.nicefact.mailmonitor.workflow.impl.task;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.nicefact.mailmonitor.core.APP_CONSTANTS;
import com.nicefact.mailmonitor.entity.AppUser;
import com.nicefact.mailmonitor.entity.LogMessage;
import com.nicefact.mailmonitor.entity.OAuthEntity;
import com.nicefact.mailmonitor.service.AppUserService;
import com.nicefact.mailmonitor.service.ContextIOService;
import com.nicefact.mailmonitor.service.LogMessageService;
import com.nicefact.mailmonitor.service.OauthService;
import com.nicefact.mailmonitor.vo.AppProperties;
import com.nicefact.mailmonitor.workflow.AbstractWorkflowTask;
import com.nicefact.mailmonitor.workflow.WorkflowContext;
import com.nicefact.mailmonitor.workflow.WorkflowExecutionException;
import com.nicefact.mailmonitor.workflow.impl.context.AuthorizeContextIOForAllDomainUsersContext;

public class AuthorizeContextIOForAllDomainUsersTask extends
		AbstractWorkflowTask {

	protected final Logger logger = Logger.getLogger(getClass().getName());

	@Autowired
	private AppProperties appProperties;
	
	@Autowired private LogMessageService logMessageService;

	@Autowired
	OauthService oauthService;

	@Autowired
	AppUserService appUserService;

	@Autowired
	private ContextIOService contextIOService;
	

	@Override
	public WorkflowContext execute(WorkflowContext context)
			throws WorkflowExecutionException {
		System.out.println("starting task");
		
		AuthorizeContextIOForAllDomainUsersContext thisContext = (AuthorizeContextIOForAllDomainUsersContext) context;
		String adminEmail = thisContext.getAdminEmail();
		LogMessage logMessage = new LogMessage();
		logMessage.setCreatedBy(adminEmail);
			try {				
				List<AppUser>  appUsers= appUserService.getAllUsers(adminEmail);
				addImapAccountForUsers(appUsers, adminEmail);
				logMessage.setMessage("All Users Synced");
			} catch (Exception e) {
				logMessage.setMessage("User Sync Failed");
				System.out.println("Error occurred : " + e.getMessage());
			}
		logMessageService.save(logMessage);
		return context;
	}

	private void addImapAccountForUsers(List<AppUser>  appUsers, String adminEmail) {
		Date fromDate = new Date();
		Date toDate = setDateRange(fromDate, false);
		for (AppUser appUser : appUsers) {
			String	user = appUser.getEmail();
			String response = contextIOService.fetchMailsByUser(user, fromDate,
					toDate);
			try {
				JSONObject jsonObject = new JSONObject(response);
				JSONArray jsonArray = jsonObject.getJSONArray("messages");
				// System.out.println("array length : " + jsonArray.length());
				if (jsonArray.length() > 0) {
					JSONObject messageObject = jsonArray.getJSONObject(0);
					if (messageObject.has("type")) {
						String messageType = (String) messageObject.get("type");
						if (messageType.equalsIgnoreCase("error") || messageType.equalsIgnoreCase("warning")) {
							System.out
									.println(user + " account or sources do not exist ");
							String resp = createAccount(adminEmail, appUser);
							//System.out.println(resp);
						}
					}
				} else {
					System.out.println(user + " is synced");
				}

			} catch (JSONException e) {
				// e.printStackTrace();
				System.out.println("error with following response : "
						+ response);
			}
		}
		

	}

	private String createAccount(String userEmail, AppUser appUser) {
		String reply = "Mail sent asking for authorization to "+ appUser.getEmail() ;
		OAuthEntity oAuthEntity = oauthService.getRequestToken(appUser.getEmail());
		if (oAuthEntity != null) {
			
			String approvalUrl = oAuthEntity.getAuthorizationUrl();
			String oauthToken = oAuthEntity.getKey();
			String oauthSecret = oAuthEntity.getSecret();
			appUser.setOauthtokensecret(oauthSecret);
			appUser.setOauthtoken(oauthToken);
			appUserService.save(appUser);
			appUserService.sendApprovalMailToUser(appProperties.getUsername(),userEmail,appUser.getEmail(), approvalUrl);
			System.out.println("approval Url : " + approvalUrl);
		} else {
			System.out.println("oauthParameters is null");
		}
		return reply;
	}
	


	private Date setDateRange(Date date, boolean dayStart) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.set(Calendar.HOUR, 0);
		cal.set(Calendar.MINUTE, 0);
		if (!dayStart) {
			cal.add(Calendar.DATE, 1);
		}
		return cal.getTime();
	}

	

}
